package com.jerry.hm.datastructure.queue;

import java.util.Iterator;

/**
 * 环形单向带哨兵链表实现
 *
 * @author Jerry
 * @since 2024/10/3 10:32
 */
public class LinkedListQueue<E> implements Queue<E>, Iterable<E> {

    static class Node<E> {

        /**
         * 下一个节点
         */
        Node<E> next;

        /**
         * 节点值
         */
        E value;

        public Node(Node next, E value) {
            this.next = next;
            this.value = value;
        }
    }

    private Node<E> head = new Node<>(null, null);
    private Node<E> tail = head;
    private int size = 0;
    private int capacity;

    public LinkedListQueue() {
        this(Integer.MAX_VALUE);
    }

    public LinkedListQueue(int capacity) {
        tail.next = head;
        this.capacity = capacity;
    }

    /**
     * 向队尾插入元素
     *
     * @param e
     * @return
     */
    @Override
    public boolean offer(E e) {
        if (isFull()) {
            return false;
        }
        Node<E> newNode = new Node<>(head, e);
        tail.next = newNode;
        tail = newNode;
        size++;
        return true;
    }

    /**
     * 从队首移除元素
     *
     * @return
     */
    @Override
    public E poll() {
        if (isEmpty()) {
            return null;
        }
        Node<E> target = head.next;
        head = head.next;
        size--;
        return target.value;
    }

    /**
     * 从队首获取元素
     *
     * @return
     */
    @Override
    public E peek() {
        if (isEmpty()) {
            return null;
        }
        return head.next.value;
    }

    /**
     * 队列是否为空
     *
     * @return
     */
    @Override
    public boolean isEmpty() {
        return head == tail;
    }

    /**
     * 队列是否已满
     *
     * @return
     */
    @Override
    public boolean isFull() {
        return size == capacity;
    }

    @Override
    public Iterator<E> iterator() {

        return new Iterator<>() {

            Node<E> cur = head.next;

            @Override
            public boolean hasNext() {
                return cur != head;
            }

            @Override
            public E next() {
                E value = cur.value;
                cur = cur.next;
                return value;
            }
        };
    }
}
